<template>
  <div class="comment-box">
    <div class="comment-input" v-if="!useForShare">
      <!-- <el-input
        ref="replyInput"
        placeholder="写下你的评论..."
        v-model="replyContent"
        @blur="inputBlur($event)"
        type="textarea">
      </el-input> -->
      <biz-at-textarea class="biz-at-textarea" ref="replyInput" search-url="/message/user/lists" name-key="displayName" v-model="replyContent" :at-users.sync="atUsers">
        <template slot="item" slot-scope="item">
          <img :src="head(item.user.head)">
          <span>{{item.user.displayName}}</span>
        </template>
        <textarea class="base-at-textarea" @input="inputContent" :placeholder="$t('wiki.detail.component.comment.pla1')" maxlength="1000" :rows="3" @blur="inputBlur($event)"></textarea>
      </biz-at-textarea>
      <common-emoji
        ref="commonEmoji"
        :input-ref="$refs.replyInput"
        @changeInput="value => replyContent = value">
      </common-emoji>
      <el-button
        :loading="addLoading"
        @click="addComment()"
        type="primary">
        {{$t('common.base.comment')}}
      </el-button>
    </div>
    <div class="comment-main">
      <h3>{{$t('common.base.allComment')}}<span class="comment-count">{{this.useForShare ? this.commentListParent.length : this.pageInfo.total}}</span></h3>
      <div class="comment-list">
        <div
          :key="comment.parentComment.id"
          v-for="comment in commentList"
          class="comment-items">
          <comment-item
            :use-for-share="useForShare"
            :is-top-comment="true"
            :comment="comment.parentComment || {}"
            :init-data="initData"
            @commentChange="commentChange"
            @refresh="refresh">
            <div class="subcomment-box" slot="subComment" v-if="comment.childrenComment && comment.childrenComment.length">
              <!-- <div :key="subComment.id" v-for="subComment in comment.childrenComment"> -->
              <comment-item
                :use-for-share="useForShare"
                :key="subComment.id"
                v-for="subComment in comment.childrenComment"
                :comment="subComment"
                @refresh="refresh"
                @commentChange="commentChange"
                :init-data="initData"
                :title="title">
              </comment-item>
              <!-- <div class="ql-container ql-snow content recommend-item-content" :class="fontClass" style="border:none">
                  <div class="ql-editor">
                    <div v-html="emojiShow(item.content)" class="wiki-content"></div>
                  </div>
                </div> -->
              <!-- </div> -->
            </div>
          </comment-item>
        </div>
      </div>
    </div>
    <list-footer
      v-if="!useForShare"
      class="list-footer"
      @search="getWikiComment()"
      :total="pageInfo.total"
      v-model="pageInfo"
      ref="listFooter"
    ></list-footer>
  </div>
</template>

<script>

import { getWikiComment, addComment } from '@src/api/Repository'
import commentItem from './components/commentItem'
import ListFooter from '@src/modules/repository/common/ListFooter';
import commonEmoji from '@src/component/emoji'
import { getOssUrl } from '@src/util/assets'
import {enCodeAtText} from '@src/util/atText'
import { cutAtTextContent } from 'pub-bbx-utils'
import { useTenantId } from '@hooks/useRootWindow.ts';

const defaultAvatar = getOssUrl('/avatar.png')

export default {
  name: 'comment-box',
  components: {
    [commentItem.name]: commentItem,
    [ListFooter.name]: ListFooter,
    [commonEmoji.name]: commonEmoji
  },
  props: {
    wikiId: {

    },
    labels: {
      type: Array,
      default: () => []
    },
    fontClass: {

    },
    initData: {
      type: Object
    },
    useForShare: {
      type: Boolean,
      default: false
    },
    commentListParent: {
      type: Array,
      default: () => []
    },
    title:{
      type:String,
      default:''
    }
  },
  data() {
    return {
      commentList: this.useForShare ? this.commentListParent : [],

      pageInfo: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },

      replyContent: '',
      addLoading: false,
      atUsers:[]
    }
  },
  mounted() {
    !this.useForShare && this.wikiId && this.getWikiComment()
  },
  watch: {
    wikiId() {
      !this.useForShare && this.getWikiComment()
    }
  },
  methods: {
    head(src){
      if(!src) return defaultAvatar;
      return src;
    },
    inputBlur(e) {
      this.$refs.commonEmoji && this.$refs.commonEmoji.contentBlur(e.target)
    },
    addEmoji(emoji) {
      this.replyContent = emoji.text
    },
    getWikiComment() {
      getWikiComment({
        wikiId: this.wikiId,
        ...this.pageInfo
      }).then(res => {
        if (res.code !== 0) {
          this.$platform.notification({
            title: res.message,
            type: 'error',
          })
          return
        }
        this.commentList = res.result?.commentList || []
        this.pageInfo.total = res.result?.pageInfo?.total || 0
      }).catch(err => {
        console.log(err)
      })
    },
    addComment() {
      if(!this.replyContent) {
        return this.$platform.notification({
          title: this.$t('wiki.detail.component.comment.tips1'),
          type: 'warning'
        })
      }

      let replyContent = enCodeAtText(this.replyContent, this.atUsers);
      let receivers = []
      this.atUsers.forEach(item=>{
        if(this.replyContent.indexOf(`${item.displayName} `) > -1){
          receivers.push(item.userId)
        }
      })
      let receiversString = receivers.join(',')    
      let query = ''
      if(this.atUsers.length > 0){
        let queryData = {
          receivers:receiversString,
          tenantId: useTenantId().value,
          content: cutAtTextContent(this.replyContent),
          sendUserName: this.initData?.userInfo?.displayName,
          bizId: this.wikiId,
          bizNo: this.title
        };
        query = '?';
        for (let i in queryData) {
          query += `&${i}=${queryData[i]}`;
        }
      }
      this.addLoading = true
      addComment({
        wikiId: this.wikiId,
        content: replyContent
      }, query).then(res => {
        if (res.code !== 0) {
          this.$platform.notification({
            title: res.message,
            type: 'error'
          })
          return
        }
        this.$platform.notification({
          title: this.$t('common.base.tip.releaseSuccess'),
          type: 'success'
        })
        this.replyContent = ''
        this.atUsers = []
        this.refresh()
        this.$emit('commentChange')
      }).catch(err => {
        console.log(err)
      })
        .finally(() => {
          this.addLoading = false
        })
    },
    refresh() {
      this.getWikiComment()
    },
    commentChange() {
      this.$emit('commentChange')
    },
    inputContent(event){
      let value = event.target.value;
      this.replyInput = value;
    },
  },
}
</script>

<style lang="scss" scoped>
  .ql-editor {
    .wiki-content {
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
      ::v-deep p {
        font-size: 14px;
        font-weight: 400;
        color: #595959;
        line-height: 20px;
      }
    }
  }
  .comment-box {
    margin-top: 12px;
    border-radius: 4px;
    background: #fff;
    padding: 32px 100px;
  }
  // ::v-deep .comment-items > .comment-item {
  //   padding: 0;
  //   & > .comment-item-main {
  //     & > .comment-item-operation {
  //       margin-bottom: 12px;
  //     }
  //   }
  // }
  // .subcomment-box {
  //   ::v-deep .comment-item {
  //     background: #F5F5F5;
  //   }
  // }
  .comment-input {
    position: relative;
    ::v-deep .el-button {
      margin-top: 12px;
      float: right;
      margin-bottom: 16px;
    }
    ::v-deep .el-textarea__inner {
      height: 70px;
      padding: 10px 22px 10px 16px;
      background: #F5F5F5;
      border-radius: 4px;
      border: 1px solid #E8E8E8;
      font-size: 14px;
      font-weight: 400;
      color: #262626 !important;
      line-height: 20px;
      &::-webkit-input-placeholder{
        color: #8C8C8C !important;
      }
      &::-moz-placeholder{
        color: #8C8C8C !important;
      }
      &:-ms-input-placeholder{
        color: #8C8C8C !important;
      }
    } 
  }
  .comment-main {
    clear: both;
    padding-top: 10px;
    border-top: 1px solid #E5E6E5;
    &>h3 {
      margin-bottom: 9px;
    }
  }
  .subcomment-box {
    margin-top: 16px;
    border-radius: 4px;
    overflow: hidden;
    // margin-bottom: 16px;
    ::v-deep .comment-item:last-child hr{
      display: none;
    }
  }
  .comment-items {
    &>.comment-item {
      border-bottom: 1px solid #E5E6E5;
    }
  }
  .comment-count {
    font-size: 16px;
    font-weight: 400;
    color: #8C8C8C;
    line-height: 22px;
    margin-left: 4px;
  }
</style>